#include "Server.h"
#include "ui_Server.h"
#include <QMessageBox>
#include <QDir>
#include <QBitmap>
#include <QStyleOption>
#include <QMouseEvent>
#include <QPainter>
#include "mymessagebox.h"

Server::Server(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Server)
    , tcpServer(new QTcpServer(this))
    , tcpServer1(new QTcpServer(this))
    , tcpServer2(new QTcpServer(this))
    , tcpServer3(new QTcpServer(this))
    , tcpServer4(new QTcpServer(this))
    , tcpServer5(new QTcpServer(this))
    , tcpServer6(new QTcpServer(this))
    , tcpServer7(new QTcpServer(this))
    , tcpServer8(new QTcpServer(this))
    , tcpServer9(new QTcpServer(this))
    , tcpServer10(new QTcpServer(this))
    , currentDate(QDate::currentDate())
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    // 点击关闭按钮关闭窗口
    connect(ui->closeButton, &QPushButton::clicked, this, &Server::close);

    // 初始化数据库
    initializeDatabase();
    createTables();

    // 启动 TCP 服务器
    connect(tcpServer, &QTcpServer::newConnection, this, &Server::onNewConnection);
    if (!tcpServer->listen(QHostAddress::Any, 12345)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer1, &QTcpServer::newConnection, this, &Server::onNewConnection1);
    if (!tcpServer1->listen(QHostAddress::Any, 12346)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer1->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer1->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer2, &QTcpServer::newConnection, this, &Server::onNewConnection2);
    if (!tcpServer2->listen(QHostAddress::Any, 12347)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer2->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer2->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer3, &QTcpServer::newConnection, this, &Server::onNewConnection3);
    if (!tcpServer3->listen(QHostAddress::Any, 12348)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer3->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer3->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer4, &QTcpServer::newConnection, this, &Server::onNewConnection4);
    if (!tcpServer4->listen(QHostAddress::Any, 12349)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer4->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer4->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer5, &QTcpServer::newConnection, this, &Server::onNewConnection5);
    if (!tcpServer5->listen(QHostAddress::Any, 12350)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer5->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer5->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer6, &QTcpServer::newConnection, this, &Server::onNewConnection6);
    if (!tcpServer6->listen(QHostAddress::Any, 12351)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer6->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer6->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer7, &QTcpServer::newConnection, this, &Server::onNewConnection7);
    if (!tcpServer7->listen(QHostAddress::Any, 12352)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer7->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer7->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer8, &QTcpServer::newConnection, this, &Server::onNewConnection8);
    if (!tcpServer8->listen(QHostAddress::Any, 12353)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer8->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer8->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer9, &QTcpServer::newConnection, this, &Server::onNewConnection9);
    if (!tcpServer9->listen(QHostAddress::Any, 12354)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer9->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer9->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    connect(tcpServer10, &QTcpServer::newConnection, this, &Server::onNewConnection10);
    if (!tcpServer10->listen(QHostAddress::Any, 12355)) {
        // QMessageBox::critical(this, "错误", "无法启动服务器: " + tcpServer10->errorString());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法启动服务器: " + tcpServer10->errorString());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }


    // 每天凌晨检查日期变化
    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Server::onDayChanged);
    timer->start(1000);  // 每1秒触发一次

    // 首次进入页面时检查并生成考勤表
    checkAttendanceGroups();
}

Server::~Server()
{
    timer->stop();
    delete ui;
}

// 实现窗口拖动功能
void Server::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Server::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Server::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Server::checkAttendanceGroups()
{
    // 查询 AttendanceGroup 表
    QSqlQuery query;
    query.prepare("SELECT 考勤组号, 考勤日期 FROM AttendanceGroup");

    if (query.exec()) {
        while (query.next()) {
            QString groupId = query.value(0).toString();  // 获取考勤组号
            QString attendanceDays = query.value(1).toString();  // 获取考勤日期

            // 解析考勤日期
            QStringList days = parseAttendanceDays(attendanceDays);

            // 检查今天是否为考勤日
            if (days.contains(QString::number(currentDate.dayOfWeek()))) {
                createAttendanceTable(groupId, currentDate);  // 创建考勤表
            }
        }
    } else {
        qDebug() << "Failed to query AttendanceGroup: " << query.lastError();
    }
}

QStringList Server::parseAttendanceDays(const QString &attendanceDays)
{
    QStringList days;
    for (int i = 0; i < attendanceDays.length(); ++i) {
        if (attendanceDays[i] == '1') {
            days << QString::number(i + 1);  // 将索引 +1 作为周几
        }
    }
    return days;
}

void Server::createAttendanceTable(const QString &groupId, const QDate &date)
{
    QString tableName = QString("`%1_%2`").arg(groupId).arg(date.toString("yyyyMMdd"));
    QString TableName = QString("%1_%2").arg(groupId).arg(date.toString("yyyyMMdd"));

    // 检查考勤表是否已存在
    QSqlQuery checkQuery;
    checkQuery.prepare(QString("SELECT name FROM sqlite_master WHERE type='table' AND name='%1'").arg(TableName));

    if (checkQuery.exec() && checkQuery.next()) {
        // 如果表已经存在，直接返回，不执行插入操作
        qDebug() << "Attendance table" << tableName << "already exists, skipping creation and insertion.";
        return;
    }

    // 创建考勤表的SQL语句
    QSqlQuery query;
    QString createTableSQL = QString(
                                 "CREATE TABLE IF NOT EXISTS %1 ("
                                 "工号 INT, 姓名 VARCHAR(50), 考勤时间 TIME, 考勤状态 INT DEFAULT 0)"
                                 ).arg(tableName);

    if (!query.exec(createTableSQL)) {
        qDebug() << "Failed to create attendance table:" << query.lastError();
        return;
    }

    // 从考勤组号表中获取工号和姓名
    QString tableName1 = QString("`%1`").arg(groupId);
    query.prepare(QString("SELECT 工号, 姓名 FROM %1").arg(tableName1));
    if (query.exec()) {
        while (query.next()) {
            int employeeId = query.value(0).toInt();
            QString name = query.value(1).toString();

            // 插入考勤信息到当天表中
            QSqlQuery insertQuery;
            insertQuery.prepare(QString("INSERT INTO %1 (工号, 姓名) VALUES (:employeeId, :name)").arg(tableName));
            insertQuery.bindValue(":employeeId", employeeId);
            insertQuery.bindValue(":name", name);

            if (!insertQuery.exec()) {
                qDebug() << "Failed to insert attendance data:" << insertQuery.lastError();
            }
        }
    } else {
        qDebug() << "Failed to query group table:" << query.lastError();
    }
}

void Server::processPreviousDay()
{
    QDate prevDate = currentDate.addDays(-1);

    // 查询所有考勤组号
    QSqlQuery query;
    query.prepare("SELECT DISTINCT 考勤组号 FROM AttendanceGroup");

    if (query.exec()) {
        while (query.next()) {
            QString groupId = query.value(0).toString();
            finalizePreviousDay(groupId, prevDate);  // 结算前日考勤表
        }
    } else {
        qDebug() << "Failed to query attendance groups for previous day processing: " << query.lastError();
    }
}

void Server::finalizePreviousDay(const QString &groupId, const QDate &prevDate)
{
    QString tableName = QString("`%1_%2`").arg(groupId).arg(prevDate.toString("yyyyMMdd"));

    // 查询前日未打卡数据
    QSqlQuery query;
    query.prepare(QString("SELECT 工号 FROM %1 WHERE 考勤状态 = 0").arg(tableName));

    if (query.exec()) {
        while (query.next()) {
            QString employeeId = query.value(0).toString();

            // 检查是否有请假记录
            QSqlQuery leaveQuery;
            leaveQuery.prepare("SELECT COUNT(*) FROM LeaveTable WHERE 工号 = :employeeId "
                               "AND 开始日期 <= :prevDate AND 结束日期 >= :prevDate "
                               "AND 申请状态 = 1 AND 考勤组号 = :groupId");
            leaveQuery.bindValue(":employeeId", employeeId);
            leaveQuery.bindValue(":prevDate", prevDate);
            leaveQuery.bindValue(":groupId", groupId);

            if (leaveQuery.exec() && leaveQuery.next() && leaveQuery.value(0).toInt() > 0) {
                updateEmployeeAttendanceSummary(employeeId, groupId, prevDate, true);  // 请假

                // 更新工号考勤状态为3（请假）
                QSqlQuery updateQuery;
                updateQuery.prepare(QString("UPDATE %1 SET 考勤状态 = 3 WHERE 工号 = :employeeId").arg(tableName));
                updateQuery.bindValue(":employeeId", employeeId);

                if (updateQuery.exec()) {
                    qDebug() << "Successfully updated attendance status to 3 for employee" << employeeId;
                } else {
                    qDebug() << "Failed to update attendance status to 3:" << updateQuery.lastError();
                }
            } else {
                updateEmployeeAttendanceSummary(employeeId, groupId, prevDate, false);  // 未打卡

                // 使用employeeId查询EmployeeInfo表，获得"姓名"
                QSqlQuery nameQuery;
                nameQuery.prepare("SELECT 姓名 FROM EmployeeInfo WHERE 工号 = :employeeId");
                nameQuery.bindValue(":employeeId", employeeId);

                if (nameQuery.exec() && nameQuery.next()) {
                    QString employeeName = nameQuery.value(0).toString();

                    // 生成表名
                    QString tableName = QString("`%1_%2_1`").arg(employeeId).arg(employeeName);

                    // 插入prevDate到生成的表
                    QSqlQuery insertQuery;
                    insertQuery.prepare(QString("INSERT INTO %1 (旷工日期, 考勤组号) VALUES (:prevDate, :groupId)").arg(tableName));
                    insertQuery.bindValue(":prevDate", prevDate);
                    insertQuery.bindValue(":groupId", groupId);

                    if (insertQuery.exec()) {
                        qDebug() << "Successfully inserted prevDate and groupId into table" << tableName;
                    } else {
                        qDebug() << "Failed to insert prevDate and groupId into table" << tableName << ":" << insertQuery.lastError();
                    }
                } else {
                    qDebug() << "Failed to query employee name from EmployeeInfo:" << nameQuery.lastError();
                }
            }
        }
    } else {
        qDebug() << "Failed to query previous day attendance table: " << query.lastError();
    }
}

void Server::updateEmployeeAttendanceSummary(const QString &employeeId, const QString &groupId, const QDate &date, bool isOnLeave)
{
    QSqlQuery query;
    QString updateSQL;

    if (isOnLeave) {
        // 请假，增加打卡总数和请假次数
        updateSQL = "UPDATE EmployeeAttendanceSummary SET 打卡总数 = 打卡总数 + 1, 请假次数 = 请假次数 + 1 WHERE 工号 = :employeeId";
    } else {
        // 未打卡，增加打卡总数和未打卡数
        updateSQL = "UPDATE EmployeeAttendanceSummary SET 打卡总数 = 打卡总数 + 1, 未打卡数 = 未打卡数 + 1 WHERE 工号 = :employeeId";
    }

    query.prepare(updateSQL);
    query.bindValue(":employeeId", employeeId);
    query.bindValue(":groupId", groupId);

    if (!query.exec()) {
        qDebug() << "Failed to update EmployeeAttendanceSummary: " << query.lastError();
    }
}

void Server::onDayChanged()
{
    QDate newDate = QDate::currentDate();
    if (newDate != currentDate) {
        // 日期已变更，执行前日结算并创建新表
        currentDate = newDate;
        processPreviousDay();
        checkAttendanceGroups();
    }
}

void Server::initializeDatabase()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("attendance_system.db");

    if (!db.open()) {
        // QMessageBox::critical(this, "错误", "无法打开数据库: " + db.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法打开数据库: " + db.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }
}

void Server::createTables()
{
    QSqlQuery query;

    // 创建员工信息表
    QString employeeInfoTable = R"(
        CREATE TABLE IF NOT EXISTS EmployeeInfo (
            工号 INT PRIMARY KEY,
            姓名 VARCHAR(50),
            密码 VARCHAR(50),
            标签号 INT
        );
    )";
    if (!query.exec(employeeInfoTable)) {
        // QMessageBox::critical(this, "错误", "无法创建员工信息表: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法创建员工信息表: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
    }

    // 创建补签表
    QString reSignTable = R"(
        CREATE TABLE IF NOT EXISTS ReSignTable (
            工号 INT,
            姓名 VARCHAR(50),
            申请时间 DATETIME,
            未打卡日期 DATE,
            补签原因 VARCHAR(255),
            申请状态 INT,
            考勤组号 INT
        );
    )";
    if (!query.exec(reSignTable)) {
        // QMessageBox::critical(this, "错误", "无法创建补签表: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法创建补签表: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
    }

    // 创建请假表
    QString leaveTable = R"(
        CREATE TABLE IF NOT EXISTS LeaveTable (
            工号 INT,
            姓名 VARCHAR(50),
            申请时间 DATETIME,
            开始日期 DATE,
            结束日期 DATE,
            请假原因 VARCHAR(255),
            申请状态 INT,
            考勤组号 INT
        );
    )";
    if (!query.exec(leaveTable)) {
        // QMessageBox::critical(this, "错误", "无法创建请假表: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法创建请假表: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
    }

    // 创建考勤组表
    QString attendanceGroupTable = R"(
        CREATE TABLE IF NOT EXISTS AttendanceGroup (
            考勤组号 INT PRIMARY KEY,
            开始时间 TIME,
            结束时间 TIME,
            考勤日期 VARCHAR(7)
        );
    )";
    if (!query.exec(attendanceGroupTable)) {
        // QMessageBox::critical(this, "错误", "无法创建考勤组表: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法创建考勤组表: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
    }

    // 创建人脸审核表
    QString faceVerificationTable = R"(
        CREATE TABLE IF NOT EXISTS FaceVerification (
            工号 INT,
            姓名 VARCHAR(50),
            申请时间 DATETIME,
            申请状态 INT
        );
    )";
    if (!query.exec(faceVerificationTable)) {
        // QMessageBox::critical(this, "错误", "无法创建人脸审核表: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法创建人脸审核表: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
    }

    // 创建员工考勤总表
    QString employeeAttendanceSummaryTable = R"(
        CREATE TABLE IF NOT EXISTS EmployeeAttendanceSummary (
            工号 INT PRIMARY KEY,
            姓名 VARCHAR(50),
            打卡总数 INT,
            已打卡数 INT,
            补签次数 INT,
            请假次数 INT,
            未打卡数 INT
        );
    )";
    if (!query.exec(employeeAttendanceSummaryTable)) {
        // QMessageBox::critical(this, "错误", "无法创建员工考勤总表: " + query.lastError().text());
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法创建员工考勤总表: " + query.lastError().text());
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

void Server::on_pushButton_clicked()
{
    Resignature *resignature = new Resignature(this);
    resignature->show();
    this->hide();
}


void Server::on_pushButton_2_clicked()
{
    Vacation *vacation = new Vacation(this);
    vacation->show();
    this->hide();
}


void Server::on_pushButton_3_clicked()
{
    Manage *manage = new Manage(this);
    manage->show();
    this->hide();
}


void Server::on_pushButton_4_clicked()
{
    Face *face = new Face(this);
    face->show();
    this->hide();
}

void Server::onNewConnection()
{
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead);
}

void Server::onReadyRead()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest(QTcpSocket *clientSocket, const QString &request)
{
    QStringList parts = request.split("|");
    if (parts.size() != 4) {
        clientSocket->write("INVALID_REQUEST");
        return;
    }

    QString employeeId = parts[0];
    QString employeeName = parts[1];
    QString password = parts[2];
    QString ensurePassword = parts[3];

    QSqlQuery query;
    query.prepare("SELECT 姓名, 密码 FROM EmployeeInfo WHERE 工号 = :employeeId");
    query.bindValue(":employeeId", employeeId);
    if (!query.exec() || !query.next()) {
        clientSocket->write("ID_NAME_MISMATCH");
        return;
    }

    QString storedName = query.value(0).toString();
    QString storedPassword = query.value(1).toString();

    if (storedName != employeeName) {
        clientSocket->write("ID_NAME_MISMATCH");
    } else if (!storedPassword.isEmpty()) {
        clientSocket->write("ALREADY_REGISTERED");
    } else if (password != ensurePassword) {
        clientSocket->write("PASSWORD_MISMATCH");
    } else {
        query.prepare("UPDATE EmployeeInfo SET 密码 = :password WHERE 工号 = :employeeId");
        query.bindValue(":password", password);
        query.bindValue(":employeeId", employeeId);
        if (query.exec()) {
            clientSocket->write("REGISTRATION_SUCCESS");
        } else {
            clientSocket->write("DATABASE_ERROR");
        }
    }
}


void Server::onNewConnection1()
{
    QTcpSocket *clientSocket = tcpServer1->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead1);
}

void Server::onReadyRead1()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest1(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest1(QTcpSocket *clientSocket, const QString &request)
{
    QStringList parts = request.split("|");
    if (parts.size() != 2) {
        clientSocket->write("INVALID_REQUEST");
        return;
    }

    QString employeeId = parts[0];
    QString password = parts[1];

    QSqlQuery query;
    query.prepare("SELECT 密码 FROM EmployeeInfo WHERE 工号 = :employeeId");
    query.bindValue(":employeeId", employeeId);
    if (!query.exec() || !query.next()) {
        clientSocket->write("ID_NOT_FOUND");
        return;
    }

    QString storedPassword = query.value(0).toString();

    if (storedPassword.isEmpty()) {
        clientSocket->write("UNVERIFIED_EMPLOYEE");
    } else if (storedPassword != password) {
        clientSocket->write("PASSWORD_ERROR");
    } else {
        clientSocket->write("LOGIN_SUCCESS");
    }
}


void Server::onNewConnection2()
{
    QTcpSocket *clientSocket = tcpServer2->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead2);
}

void Server::onReadyRead2()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest2(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest2(QTcpSocket *clientSocket, const QString &request)
{
    QStringList parts = request.split("|");
    QString command = parts[0];

    if (command == "GET_EMPLOYEE_INFO") {
        QString employeeId = parts[1];

        // 查询数据库，获取工号和姓名
        QSqlQuery query;
        QString employeeName;
        int employeeNumber;

        // 查询EmployeeInfo表获取员工信息
        query.prepare("SELECT 工号, 姓名 FROM EmployeeInfo WHERE 工号 = :employeeId");
        query.bindValue(":employeeId", employeeId);

        if (query.exec()) {
            if (query.next()) {
                employeeNumber = query.value(0).toInt();
                employeeName = query.value(1).toString();

                // 查询名为"工号_姓名"的表，获取考勤组号
                QString tableName = QString("`%1_%2`").arg(employeeNumber).arg(employeeName);
                query.prepare(QString("SELECT 考勤组号 FROM %1").arg(tableName));

                QStringList attendanceGroups;
                if (query.exec()) {
                    while (query.next()) {
                        attendanceGroups.append(query.value(0).toString());
                    }
                } else {
                    qDebug() << "查询考勤组失败: " << query.lastError();
                }

                // 构建响应并通过TCP传输
                QString response = QString("EMPLOYEE_INFO|%1|%2|%3")
                                       .arg(employeeId)
                                       .arg(employeeName)
                                       .arg(attendanceGroups.join("|"));
                clientSocket->write(response.toUtf8());

            } else {
                qDebug() << "未找到员工信息";
            }
        } else {
            qDebug() << "查询员工信息失败: " << query.lastError();
        }

    } else if (command == "GET_ATTENDANCE_GROUP_INFO") {
        QString groupId = parts[1];

        // 查询AttendanceGroup表获取考勤组信息
        QSqlQuery query;
        QString startTime;
        QString endTime;
        QString attendanceDays;

        query.prepare("SELECT 开始时间, 结束时间, 考勤日期 FROM AttendanceGroup WHERE 考勤组号 = :groupId");
        query.bindValue(":groupId", groupId);

        if (query.exec()) {
            if (query.next()) {
                startTime = query.value(0).toString();
                endTime = query.value(1).toString();
                attendanceDays = query.value(2).toString();

                // 构建响应并通过TCP传输
                QString response = QString("ATTENDANCE_GROUP|%1|%2|%3")
                                       .arg(startTime)
                                       .arg(endTime)
                                       .arg(attendanceDays);
                clientSocket->write(response.toUtf8());

            } else {
                qDebug() << "未找到考勤组信息";
            }
        } else {
            qDebug() << "查询考勤组信息失败: " << query.lastError();
        }
    }
}


void Server::onNewConnection3()
{
    QTcpSocket *clientSocket = tcpServer3->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead3);
}

void Server::onReadyRead3()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest3(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest3(QTcpSocket *clientSocket, const QString &request)
{
    QStringList requestParts = request.split("|");

    if (requestParts[0] == "CHANGE_PASSWORD") {
        QString employeeId = requestParts[1];
        QString oldPassword = requestParts[2];
        QString newPassword = requestParts[3];

        QSqlQuery query;
        query.prepare("SELECT 密码 FROM EmployeeInfo WHERE 工号 = :employeeId");
        query.bindValue(":employeeId", employeeId);

        if (query.exec() && query.next()) {
            QString currentPassword = query.value(0).toString();

            if (currentPassword != oldPassword) {
                // 返回密码不匹配
                clientSocket->write("PASSWORD_MISMATCH");
            } else {
                // 更新密码
                query.prepare("UPDATE EmployeeInfo SET 密码 = :newPassword WHERE 工号 = :employeeId");
                query.bindValue(":newPassword", newPassword);
                query.bindValue(":employeeId", employeeId);

                if (query.exec()) {
                    clientSocket->write("PASSWORD_CHANGED");
                } else {
                    qDebug() << "更新密码失败: " << query.lastError().text();
                }
            }
        } else {
            qDebug() << "查询员工信息失败: " << query.lastError().text();
        }
    }
}


void Server::onNewConnection4()
{
    QTcpSocket *clientSocket = tcpServer4->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead4);
}

void Server::onReadyRead4()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest4(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest4(QTcpSocket *clientSocket, const QString &request)
{
    if (request.startsWith("DATA:")) {
        // 处理工号和时间数据
        QStringList parts = request.mid(5).split("|");
        QString employeeId = parts[0];
        QString currentTime = parts[1];

        // 查询 EmployeeInfo 表，获取员工姓名
        QSqlQuery query;
        query.prepare("SELECT 姓名 FROM EmployeeInfo WHERE 工号 = :employeeId");
        query.bindValue(":employeeId", employeeId);
        query.exec();

        if (query.next()) {
            QString employeeName = query.value(0).toString();

            // 插入数据到 FaceVerification 表
            QSqlQuery insertQuery;
            insertQuery.prepare("INSERT INTO FaceVerification (工号, 姓名, 申请时间, 申请状态) "
                                "VALUES (:employeeId, :name, :requestTime, 0)");
            insertQuery.bindValue(":employeeId", employeeId);
            insertQuery.bindValue(":name", employeeName);
            insertQuery.bindValue(":requestTime", currentTime);
            insertQuery.exec();

            clientSocket->write("SUCCESS");

            qDebug() << "插入数据成功：" << employeeId << " " << employeeName << " " << currentTime;
        } else {
            clientSocket->write("FAIL");

            qDebug() << "未找到该工号的员工信息";
        }

        db.close();
    }
    else if (request.startsWith("FILE:")) {
        // 处理文件传输
        QStringList parts = request.mid(5).split("|");
        if (parts.size() < 3) {
            qDebug() << "请求格式不正确";
            return;
        }

        QString employeeId = parts[0];   // 工号
        QString fileName = parts[1];     // 文件名
        QByteArray fileContent = QByteArray::fromBase64(parts[2].toUtf8());  // 文件内容 (Base64 解码)

        // 以 employeeId 创建文件夹
        QString saveDirPath = QDir::currentPath() + "/" + employeeId;
        QDir dir(saveDirPath);
        if (!dir.exists()) { // 如果目录不存在
            if (!dir.mkpath(".")) { // 尝试创建目录
                // 如果创建失败
                qDebug() << "Failed to create directory: " << saveDirPath;
                return;
            }
        }

        // 保存文件到以 employeeId 命名的目录
        QFile file(saveDirPath + "/" + fileName);
        if (file.open(QIODevice::WriteOnly)) {
            file.write(fileContent);
            file.close();
            qDebug() << "接收到文件并保存：" << file.fileName();
        } else {
            qDebug() << "无法打开文件进行写入：" << file.fileName();
        }
    }

}

void Server::onNewConnection5()
{
    QTcpSocket *clientSocket = tcpServer5->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead5);
}

void Server::onReadyRead5()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest5(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest5(QTcpSocket *clientSocket, const QString &request)
{
    if (request.startsWith("VACAT_TAG:")) {
        QString employeeId = request.mid(10);

        // 查询数据库中的 tag ID
        QSqlQuery query;
        query.prepare("SELECT 标签号 FROM EmployeeInfo WHERE 工号 = ?");
        query.addBindValue(employeeId.toInt());
        if (query.exec() && query.next()) {
            int tag = query.value(0).toInt();

            if (tag == 0) {
                clientSocket->write("TAG_0");
            } else {
                clientSocket->write("VAC_OK");
            }
        } else {
            clientSocket->write("ERROR");
        }
        clientSocket->flush();
    } else if (request.startsWith("RESIG_TAG:")) {
        QString employeeId = request.mid(10);

        // 查询数据库中的 tag ID
        QSqlQuery query;
        query.prepare("SELECT 标签号 FROM EmployeeInfo WHERE 工号 = ?");
        query.addBindValue(employeeId.toInt());
        if (query.exec() && query.next()) {
            int tag = query.value(0).toInt();

            if (tag == 0) {
                clientSocket->write("TAG_0");
            } else {
                clientSocket->write("RES_OK");
            }
        } else {
            clientSocket->write("ERROR");
        }
        clientSocket->flush();
    } else if (request.startsWith("SITUA_TAG:")) {
        QString employeeId = request.mid(10);

        // 查询数据库中的 tag ID
        QSqlQuery query;
        query.prepare("SELECT 标签号 FROM EmployeeInfo WHERE 工号 = ?");
        query.addBindValue(employeeId.toInt());
        if (query.exec() && query.next()) {
            int tag = query.value(0).toInt();

            if (tag == 0) {
                clientSocket->write("TAG_0");
            } else {
                clientSocket->write("SIT_OK");
            }
        } else {
            clientSocket->write("ERROR");
        }
        clientSocket->flush();
    }
}

void Server::onNewConnection6()
{
    QTcpSocket *clientSocket = tcpServer6->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead6);
}

void Server::onReadyRead6()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest6(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest6(QTcpSocket *clientSocket, const QString &request)
{
    if (request.startsWith("FETCH_DATA:")) {
        QString employeeId = request.mid(11);

        // 查询 ReSignTable 数据
        QStringList resignatureData = fetchTableData(employeeId, "ReSignTable");

        // 查询 LeaveTable 数据
        QStringList leaveData = fetchTableData(employeeId, "LeaveTable");

        // 查询 FaceVerification 数据
        QStringList faceData = fetchTableData(employeeId, "FaceVerification");

        // 拼接数据返回客户端
        QString response = resignatureData.join(";") + ";LEAVE_START;" +
                           leaveData.join(";") + ";FACE_START;" +
                           faceData.join(";");

        clientSocket->write(response.toUtf8());
        clientSocket->flush();
    }
}

QStringList Server::fetchTableData(const QString &employeeId, const QString &tableName)
{
    QStringList result;
    QSqlQuery query;
    QString queryString = QString("SELECT 申请时间, 申请状态 FROM %1 WHERE 工号 = ?").arg(tableName);
    query.prepare(queryString);
    query.addBindValue(employeeId.toInt());

    if (query.exec()) {
        while (query.next()) {
            QString time = query.value(0).toString();
            int status = query.value(1).toInt();
            result.append(time + "," + QString::number(status));
        }
    }

    return result;
}

void Server::onNewConnection7()
{
    QTcpSocket *clientSocket = tcpServer7->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead7);
}

void Server::onReadyRead7()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest7(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest7(QTcpSocket *clientSocket, const QString &request)
{
    QStringList parts = request.split("|");
    QString command = parts[0];

    if (command == "GET_GROUPS") {
        QString employeeId = parts[1];
        QString employeeName = getEmployeeName(employeeId);
        QString tableName = QString("`%1_%2`").arg(employeeId).arg(employeeName);

        // 查询考勤组号
        QStringList groupIds = getAttendanceGroupIds(tableName);
        if (groupIds.isEmpty()) {
            clientSocket->write("GROUPS|NO_GROUP");
        } else {
            QString response = "GROUPS|" + groupIds.join("|");
            clientSocket->write(response.toUtf8());
        }

    } else if (command == "GET_DATES") {
        QString employeeId = parts[1];
        QString groupId = parts[2];
        QString employeeName = getEmployeeName(employeeId);
        QString tableName = QString("`%1_%2_1`").arg(employeeId).arg(employeeName);

        // 查询旷工日期
        QStringList absenteeDates = getAbsenteeDates(tableName, groupId);
        if (absenteeDates.isEmpty()) {
            clientSocket->write("DATES|NO_DATES");
        } else {
            QString response = "DATES|" + absenteeDates.join("|");
            clientSocket->write(response.toUtf8());
        }

    } else if (command == "SUBMIT") {
        QString employeeId = parts[1];
        QString groupId = parts[2];
        QString absenteeDate = parts[3];
        QString reason = parts[4];

        QString employeeName = getEmployeeName(employeeId);
        QDateTime currentTime = QDateTime::currentDateTime();

        // 插入到ReSignTable
        QSqlQuery query;
        query.prepare("INSERT INTO ReSignTable (工号, 姓名, 申请时间, 未打卡日期, 补签原因, 申请状态, 考勤组号) "
                      "VALUES (:employeeId, :employeeName, :applyTime, :absenteeDate, :reason, 0, :groupId)");
        query.bindValue(":employeeId", employeeId);
        query.bindValue(":employeeName", employeeName);
        query.bindValue(":applyTime", currentTime);
        query.bindValue(":absenteeDate", absenteeDate);
        query.bindValue(":reason", reason);
        query.bindValue(":groupId", groupId);

        if (query.exec()) {
            clientSocket->write("SUBMIT_SUCCESS");
        } else {
            clientSocket->write("SUBMIT_FAILED");
        }
    }
}

QString Server::getEmployeeName(const QString &employeeId)
{
    QSqlQuery query;
    query.prepare("SELECT 姓名 FROM EmployeeInfo WHERE 工号 = :employeeId");
    query.bindValue(":employeeId", employeeId);
    if (query.exec() && query.next()) {
        return query.value(0).toString();
    }
    return "";
}

QStringList Server::getAttendanceGroupIds(const QString &tableName)
{
    QStringList groupIds;
    QSqlQuery query;
    QString queryString = QString("SELECT 考勤组号 FROM %1").arg(tableName);  // 动态表名
    if (query.exec(queryString)) {
        while (query.next()) {
            groupIds << query.value(0).toString();
        }
    }
    return groupIds;
}

QStringList Server::getAbsenteeDates(const QString &tableName, const QString &groupId)
{
    QStringList absenteeDates;
    QSqlQuery query;
    query.prepare(QString("SELECT 旷工日期 FROM %1 WHERE 考勤组号 = :groupId").arg(tableName));
    query.bindValue(":groupId", groupId);
    if (query.exec()) {
        while (query.next()) {
            absenteeDates << query.value(0).toString();
        }
    }
    return absenteeDates;
}

void Server::onNewConnection8()
{
    QTcpSocket *clientSocket = tcpServer8->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead8);
}

void Server::onReadyRead8()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest8(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest8(QTcpSocket *clientSocket, const QString &request)
{
    QStringList parts = request.split("|");
    QString command = parts[0];

    if (command == "GET_GROUPS") {
        QString employeeId = parts[1];
        QString employeeName = getEmployeeName(employeeId);
        QString tableName = QString("`%1_%2`").arg(employeeId).arg(employeeName);

        QStringList groupIds = getAttendanceGroupIds(tableName);
        if (groupIds.isEmpty()) {
            clientSocket->write("GROUPS|NO_GROUP");
        } else {
            QString response = "GROUPS|" + groupIds.join("|");
            clientSocket->write(response.toUtf8());
        }
    } else if (command == "SUBMIT") {
        QString employeeId = parts[1];
        QString groupId = parts[2];
        QString startDate = parts[3];
        QString endDate = parts[4];
        QString reason = parts[5];

        QString employeeName = getEmployeeName(employeeId);
        if (insertLeaveApplication(employeeId, employeeName, groupId, startDate, endDate, reason)) {
            clientSocket->write("SUBMIT_SUCCESS");
        } else {
            clientSocket->write("SUBMIT_FAILED");
        }
    }
}

bool Server::insertLeaveApplication(const QString &employeeId, const QString &employeeName, const QString &groupId, const QString &startDate, const QString &endDate, const QString &reason)
{
    QDateTime currentTime = QDateTime::currentDateTime();

    QSqlQuery query;
    query.prepare("INSERT INTO LeaveTable (工号, 姓名, 申请时间, 开始日期, 结束日期, 请假原因, 申请状态, 考勤组号) "
                  "VALUES (:employeeId, :employeeName, :applyTime, :startDate, :endDate, :reason, 0, :groupId)");
    query.bindValue(":employeeId", employeeId);
    query.bindValue(":employeeName", employeeName);
    query.bindValue(":applyTime", currentTime);
    query.bindValue(":startDate", startDate);
    query.bindValue(":endDate", endDate);
    query.bindValue(":reason", reason);
    query.bindValue(":groupId", groupId);

    return query.exec();
}

void Server::onNewConnection9()
{
    QTcpSocket *clientSocket = tcpServer9->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead9);
}

void Server::onReadyRead9()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest9(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest9(QTcpSocket *clientSocket, const QString &request)
{
    if (request.startsWith("GET_ATTENDANCE_SUMMARY|")) {
        QString employeeId = request.split("|")[1];

        // 查询EmployeeAttendanceSummary表
        QSqlQuery query;
        query.prepare("SELECT 打卡总数, 已打卡数, 补签次数, 请假次数, 未打卡数 FROM EmployeeAttendanceSummary WHERE 工号 = :employeeId");
        query.bindValue(":employeeId", employeeId);
        if (query.exec() && query.next()) {
            int totalCheckIns = query.value(0).toInt();
            int successfulCheckIns = query.value(1).toInt();
            int resignCounts = query.value(2).toInt();
            int leaveCounts = query.value(3).toInt();
            int missingCheckIns = query.value(4).toInt();

            QString response = QString("SUMMARY|%1|%2|%3|%4|%5")
                                   .arg(totalCheckIns)
                                   .arg(successfulCheckIns)
                                   .arg(resignCounts)
                                   .arg(leaveCounts)
                                   .arg(missingCheckIns);
            clientSocket->write(response.toUtf8());
        } else {
            clientSocket->write("SUMMARY|ERROR");
        }
    }
}


void Server::onNewConnection10()
{
    QTcpSocket *clientSocket = tcpServer10->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::onReadyRead10);
}

void Server::onReadyRead10()
{
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
    QByteArray data = clientSocket->readAll();
    QString request = QString::fromUtf8(data);

    handleClientRequest10(clientSocket, request);  // 处理客户端请求
}

void Server::handleClientRequest10(QTcpSocket *clientSocket, const QString &request)
{
    int label = request.toInt(); // 将接收到的标签转换为整数

    // 查询EmployeeInfo表
    QSqlQuery query;
    query.prepare("SELECT 工号, 姓名 FROM EmployeeInfo WHERE 标签号 = :label");
    query.bindValue(":label", label);
    if (!query.exec() || !query.next()) {
        clientSocket->write("NOT_FOUND\n"); // 添加换行符
        return;
    }

    int employeeID = query.value(0).toInt();
    QString employeeName = query.value(1).toString();

    // 查询考勤组号
    QString groupQueryStr = QString("SELECT 考勤组号 FROM `%1_%2`").arg(employeeID).arg(employeeName);
    QSqlQuery groupQuery(groupQueryStr);

    QStringList attendanceGroups;
    while (groupQuery.next()) {
        attendanceGroups << groupQuery.value(0).toString();
    }

    // 判断是否为空
    if (attendanceGroups.isEmpty()) {
        clientSocket->write("NO_ATTENDANCE\n");
        return;  // 直接返回，避免继续执行后续代码
    }

    for (const QString &groupID : attendanceGroups) {
        // 查询考勤时间和考勤日期
        QSqlQuery attendanceQuery;
        attendanceQuery.prepare("SELECT 开始时间, 结束时间, 考勤日期 FROM AttendanceGroup WHERE 考勤组号 = :groupID");
        attendanceQuery.bindValue(":groupID", groupID);
        if (!attendanceQuery.exec() || !attendanceQuery.next()) continue;

        QTime startTime = attendanceQuery.value(0).toTime();
        QTime endTime = attendanceQuery.value(1).toTime();
        QString attendanceDate = attendanceQuery.value(2).toString();

        // 解析考勤日期
        QString weekDays = attendanceDate; // attendanceDate 是一个 7 字符串
        int todayWeekDay = QDate::currentDate().dayOfWeek(); // 获取今天是星期几

        if (weekDays.at(todayWeekDay - 1) != '1') {
            clientSocket->write(QString("NO_ATTENDANCE-%1\n").arg(groupID).toUtf8()); // 添加换行符
            continue; // 如果今天不是考勤日期，则跳过
        }

        // 检查时间
        if (QTime::currentTime() < startTime || QTime::currentTime() > endTime) {
            clientSocket->write(QString("NOT_IN_TIME-%1\n").arg(groupID).toUtf8()); // 添加换行符
            continue; // 当前时间不在考勤时间段内
        }

        // 更新考勤状态
        QString tableName = QString("`%1_%2`").arg(groupID).arg(QDate::currentDate().toString("yyyyMMdd"));

        QSqlQuery checkQuery;
        checkQuery.prepare(QString("SELECT 考勤状态 FROM %1 WHERE 工号 = :id AND 姓名 = :name").arg(tableName));
        checkQuery.bindValue(":id", employeeID);
        checkQuery.bindValue(":name", employeeName);

        if (!checkQuery.exec()) {
            qDebug() << "SQL Error (check):" << checkQuery.lastError().text();  // 输出错误信息
        }

        if (checkQuery.next()) {
            int attendanceStatus = checkQuery.value(0).toInt();
            if (attendanceStatus == 1) {
                // 如果考勤状态已经是 1，则发送重复打卡信息
                clientSocket->write(QString("DUPLICATE_ATTENDANCE-%1\n").arg(groupID).toUtf8());
                continue;
            }
        }

        QSqlQuery updateAttendanceQuery;
        QTime currentTime = QTime::currentTime();  // 获取当前时间
        updateAttendanceQuery.prepare(QString("UPDATE %1 SET 考勤时间 = :currentTime, 考勤状态 = 1 WHERE 工号 = :id AND 姓名 = :name").arg(tableName));
        updateAttendanceQuery.bindValue(":currentTime", currentTime.toString("HH:mm:ss"));  // 绑定当前时间（时:分:秒）
        updateAttendanceQuery.bindValue(":id", employeeID);
        updateAttendanceQuery.bindValue(":name", employeeName);

        if (!updateAttendanceQuery.exec()) {
            qDebug() << "SQL Error:" << updateAttendanceQuery.lastError().text();  // 输出错误信息
        }

        // 更新考勤总结
        QSqlQuery updateSummaryQuery;
        updateSummaryQuery.prepare("UPDATE EmployeeAttendanceSummary SET 打卡总数 = 打卡总数 + 1, 已打卡数 = 已打卡数 + 1 WHERE 工号 = :id AND 姓名 = :name");
        updateSummaryQuery.bindValue(":id", employeeID);
        updateSummaryQuery.bindValue(":name", employeeName);
        updateSummaryQuery.exec();

        clientSocket->write(QString("SUCCESS-%1-%2\n").arg(employeeName).arg(groupID).toUtf8()); // 添加换行符
        continue; // 成功处理后继续
    }

}

